// pages/myCustom/myCustom.js
var util = require('../../utils/util.js');
var pay = require('../../utils/pay.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: {
      pageNo: 0,
      pageSize: 8
    },
    customs: [],
    hidden: false,
    scrollTop: 0,
    scrollHeight: 0,
    hasMore: true,
    priviewImages:{},
    loadingText:'加载中...'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });
    this.getCustoms();
  },
  //查询定制列表
  getCustoms:function(){
    var that = this;
    wx.request({
      url: getApp().globalData.host + 'bizportal/my/buyer/customization/list',
      data: {pageSize: that.data.page.pageSize, pageIndex: that.data.page.pageNo},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        let customs = that.data.customs;
        if (res.data.records == '' || res.data.records == null || typeof(res.data.records)=='undefined' ||res.data.records.length==0) {
          that.setData({
            hidden: true,
            hasMore: false
          });
          if(customs.length>0)
            return;
        }
        for (let i = 0; i < res.data.records.length; i++) {
          let summary = res.data.records[i].summary;
          if(null!=summary&&summary.length>5){
            summary = summary.replace("定制茶品（",'');
            summary = summary.replace("）",'');
          }
          res.data.records[i].summary = summary;
          res.data.records[i].orderCreateTime = util.formatDate(res.data.records[i].orderCreateTime);
          res.data.records[i].orderPayTime = util.formatDate(res.data.records[i].orderPayTime);
          res.data.records[i].orderDeliveryTime = util.formatDate(res.data.records[i].orderDeliveryTime);
          res.data.records[i].orderReceivingTime = util.formatDate(res.data.records[i].orderReceivingTime);
          if(null!=res.data.records[i].imageUrl){
            res.data.records[i].imageUrl = getApp().globalData.imgHost + res.data.records[i].imageUrl + "/x100";
          }
          customs.push(res.data.records[i]);
        }
        that.data.page.pageNo++;
        that.setData({
          customs: customs,
          hidden: true,
          hasMore:true
        });
      },
      fail: function (res) { },
      complete: function (res) { }
    })
  },
  bindDownLoad:function(){
    var that = this;
    if (that.data.hasMore) {
      that.getCustoms();
      //查询期间设置为不得再次查询
      that.setData({
        hasMore: false
      });
    }
  },
  //预览设计图
  previewImg:function(e){
    let index = e.target.dataset.index;
    let itemId = this.data.customs[index].customizationId;
    let itemImg = this.data.customs[index].imageUrl;
    if(typeof(itemImg)!="undefined"&&itemImg!=null){ //定制已生成图片
      let obj = {url:itemImg}
      if(itemImg.indexOf("x100")>0)
        obj = {url:itemImg.substr(0,itemImg.length-5)}
      this.data.priviewImages[itemId] = obj;
    }
    //预览图暂存本地previewImg中，key为convertToHash.md5(若无变化，则不请求新的预览图)
    if (this.data.priviewImages[itemId] != null && typeof(this.data.priviewImages[itemId].url)!="undefined" 
      && this.data.priviewImages[itemId].url.length > 0) {
      let urls = [];
      urls.push(this.data.priviewImages[itemId].url);
      wx.previewImage({
        urls: urls
      })
      return;
    }

    //再请求服务器
    let that = this;
    that.setData({
      hidden: false,
      loadingText: '生成图片中...'
    })
    wx.request({
      url: getApp().globalData.host + 'bizportal/my/buyer/customization/previewMyCustom',
      header: getApp().globalData.header,
      data: { customId: itemId },
      method: 'POST',
      success: function (res) {
        if (typeof (res.data) != 'undefined' && res.data.length > 0) {
          wx.downloadFile({
            url: getApp().globalData.host + res.data,
            success: function (res) {
              let obj = {
                url: res.tempFilePath
              }
              that.data.priviewImages[itemId] = obj;
              that.data.customs[index].imageUrl = res.tempFilePath;
              that.setData({
                priviewImages: that.data.priviewImages,
                customs:that.data.customs,
                hidden: true
              })
              let urls = [];
              urls.push(that.data.priviewImages[itemId].url);
              wx.previewImage({
                urls: urls
              })
            }
          })
        }else{
          that.setData({
            hidden: true
          })
          wx.showToast({
            title: "生成失败",
          })
        }
      }
    })
  },
  //系统分享入口
  onShareAppMessage: function (e) {
    let index = e.target.dataset.index;
    let hash = this.data.customs[index].desc;
    return {
      title: '[分享] 我的定制茶叶',
      imageUrl:'https://www.ynittc.cn/resources/frontPage/images/logo.jpg',
      path: '/pages/custom/custom?' + hash.substr(4, hash.length)
    }
  },
  //再次购买
  buyAgain:function(e){
    let index = e.target.dataset.index;
    let hash = this.data.customs[index].desc;
    wx.navigateTo({
      url: '../custom/custom?' + hash.substr(4, hash.length)
    })
  },
  //查看物流详情
  showExpress:function(e){
    let index = e.target.dataset.index;
    wx.navigateTo({
      url: '../express/express?orderId=' + this.data.customs[index].orderId,
    })
  },
  //去付款
  doPay:function(e){
    let index = e.target.dataset.index;
    let orderId = this.data.customs[index].orderId;
    wx.request({
      //url: getApp().globalData.host + 'webapp/orders/detail.html',
      url: getApp().globalData.host + 'order/orderToConfirm',
      data: { orderId: orderId},
      header: getApp().globalData.header,
      method:'POST',
      success: function (res) {
        if(typeof(res.data.order)!='undefined'&&res.data.order.orderId.length>0){
          pay.toPay(res.data.order,'');
        }
      },
      fail: function (res) { },
      complete: function (res) { }
    })    
  },
  //确认收货
  confirmDelivery:function(e){
    let index = e.currentTarget.dataset.index;
    let orderId = this.data.customs[index].orderId;
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认已收到商品？',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: that.data.host + 'bizportal/my/buyer/order/orderPending/confirmDelivery',
            data: { orderId: orderId},
            header: getApp().globalData.header,
            method: 'POST',
            success: function (res) {
              if(res.data.errorCode==0){
                that.data.customs[index].orderStatus = 'Received';
                that.setData({
                  customs: that.data.customs
                });
              }else{
                wx.showToast({
                  title: "确认失败",
                })
              }
            },
            fail: function (res) { },
            complete: function (res) { }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})